<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>领取会员卡</title>
<link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/1.1.3/weui.min.css">
<body>
	<div class="page">
		<div class="page__bd page__bd_spacing">
			<a id="receiveCardBtn" href="javascript:;" class="weui-btn weui-btn_primary">领取会员卡</a>
		</div>
	</div>
</body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script src="https://res.wx.qq.com/open/libs/weuijs/1.1.4/weui.min.js"></script>
<script src="js/url.js"></script>
<script type="text/javascript">
$(function(){
	
	var appId = getUrlParam('state');
	var code = getUrlParam('code');
	console.log('code', code);
	
	$.ajax({
		async: false,
		url: DOMAIN_NAME + '/weixin/jsSdkConfig',
		type: 'POST',
		contentType: 'application/json;charset=utf-8',
		dataType: 'json',
		data: JSON.stringify({
			'appId': appId,
			'url': DOMAIN_NAME + '/member_card_receive.html'
		}),
		success(result,status,xhr){
			if(status == 'success') {
				wx.config( {
					debug : false, 
					appId : appId, 
					timestamp : result.timestamp, 
					nonceStr : result.nonceStr, 
					signature : result.signature,
					jsApiList : [ 
						'addCard'
					]
				});
				
				wx.ready(function() { 
					$('#receiveCardBtn').click(function(){
						receiveCard(appId, code);
					});
				});			
				
				wx.error(function(res) {
					console.log('wx.error', res);
				});
			}
		}, 
		error(xhr,status,error){
			console.log('status', status);
			console.log('error', error);
		}
	});
});

function receiveCard(appId, code){
	$('#receiveCardBtn').addClass('weui-btn_loading');
	$('#receiveCardBtn').prepend('<i class="weui-loading"></i>');
	
	$.ajax({
		async: false,
		url: DOMAIN_NAME + '/weixin/memberCard/cardExt',
		type: 'POST',
		contentType: 'application/json;charset=utf-8',
		dataType: 'json',
		data: JSON.stringify({
			'appId': appId,
			'code': code,
			'outerStr': 'H5',
		}),
		success(result,status,xhr){
			if(status == 'success') {
				console.log('result', result);
				console.log('cardExt', JSON.stringify(result.cardExt));
			
				wx.addCard({
					// 需要添加的卡券列表
					cardList: [{
						cardId: result.cardId,
						cardExt: JSON.stringify(result.cardExt)
					}], 
					success: function (res) {
						alert(JSON.stringify(res));
						
						$('#receiveCardBtn').removeClass('weui-btn_loading');
						$('.weui-loading').remove();
					}
				});
			}
		}, 
		error(xhr,status,error){
			console.log('status', status);
			console.log('error', error);
		}
	});
}
</script>
</head>
</html>